
// Copyright (C) 2007 Richard Uhler
// This file is part of Esiply.
//
// Esiply is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License, Version 2,
// as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

#include "Boolean.h"
#include "EsniFunction.h"
#include "HostValue.h"
#include "HostContext.h"
#include "Number.h"
#include "Scope.h"
#include "String.h"
#include "esni.h"
#include "esiply.h"

// esni_value_t is Value*
// esni_context_t is Scope*

esni_value_t esni_make_number(esni_context_t context, double value)
{
    return new Number(value);
}

esni_value_t esni_make_string(esni_context_t context, const char* value)
{
    return new String(value);
}

esni_value_t esni_make_boolean(esni_context_t context, int value)
{
    return new Boolean(value);
}

esni_value_t esni_make_function(esni_context_t context,
        esni_function_t function, const char* params)
{
    return new EsniFunction((Scope*)context, function, params);
}

double esni_get_number(esni_context_t context, esni_value_t value)
{
    return ((Value*)value)->toNumber()->get_value();
}

int esni_get_boolean(esni_context_t context, esni_value_t value)
{
    return ((Value*)value)->toBoolean()->isTrue();
}

const char* esni_get_string(esni_context_t context, esni_value_t value)
{
    return ((Value*)value)->toString()->c_str();
}

esni_value_t esni_evaluate(esni_context_t context, const char* program,
        esni_value_t* arg1, esni_value_t* arg2)
{
    HostContext hc((Scope*)context);
    HostValue* hv1 = arg1 ? new HostValue((Value*)*arg1) : NULL;
    HostValue* hv2 = arg2 ? new HostValue((Value*)*arg2) : NULL;
    HostValue res = hc.host_eval(program, hv1, hv2);
    if (arg1)
    {
        *arg1 = hv1->get_value();
    }
    if (arg2)
    {
        *arg2 = hv2->get_value();
    }
    return res.get_value();
}

esni_value_t esni_run_file(esni_context_t context, const char* filename)
{
    HostContext hc((Scope*)context);
    return hc.run_file(filename).get_value();
}

esni_context_t esni_create(const char* libdir)
{
    return esiply_init(libdir).get_scope();
}

esni_interface_t esni_interface = {
    esni_make_number,
    esni_make_string,
    esni_make_boolean,
    esni_make_function,
    esni_get_number,
    esni_get_boolean,
    esni_get_string,
    esni_evaluate,
    esni_run_file,
    esni_create
};

esni_interface_t* esni_get_interface()
{
    return &esni_interface;
}

